<?php
namespace App\Http\Controllers\Web;

use App\Events\RegSuccess;
use App\Http\Controllers\Controller;
use App\Models\MUser;
use App\Utils\TreeUtil;
use DB;
use Exception;
use Illuminate\Http\Request;

/**
 * 用户登录管理
 */
class LoginController extends Controller
{

    /**
     * 会员前台注册页面
     */
    public function registerPage($no = "")
    {
        $this->data['puser'] = MUser::where('no', $no)->first();
        return view('system.reg_user')->with($this->data);
    }

    /**
     * 注册新的会员
     */
    public function registerAct(Request $request)
    {
        if (!$this->validateReq($request, MUser::regRulesWithMsg(0), MUser::regRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }
        $user = new MUser();

        //检查会员是否重名
        if ($user->existUserName($request->username)) {
            $this->data = $this->makeJsCode(1, "用户名已经存在！");
            return response()->json($this->data);
        }

        //检查报单中心
        $bdzx = TreeUtil::checkBdzxByName($request->bdzx);
        if (empty($bdzx)) {
            $this->data = $this->makeJsCode(1, "无效的报单中心！");
            return response()->json($this->data);
        }

        //检查推荐人
        $puser = TreeUtil::checkPUserByName($request->pname);
        if (empty($puser)) {
            $this->data = $this->makeJsCode(1, "无效的推荐人！");
            return response()->json($this->data);
        }

        //检查节点人
        $addr = MUser::$ADDR_NO;
        $nuser = TreeUtil::checkNUserByName($request->nname);
        if (empty($nuser)) {
            $this->data = $this->makeJsCode(1, "无效的节点人！");
            return response()->json($this->data);
        } else {//判断节点是否有位置
            $addr = TreeUtil::getNodeAddrByUser($nuser);
            if ($addr == MUser::$ADDR_NO) {
                $this->data = $this->makeJsCode(1, "节点人位置已满！");
                return response()->json($this->data);
            }
        }

        try {
            DB::transaction(function () use ($request, $puser, $nuser, $bdzx, $addr, &$user) {
                if ($user->regUser($request, $puser, $nuser, $bdzx, $addr)) {

                    event(new RegSuccess($user));   //发送注册成功事件通知
                    $this->data = $this->makeJsCode(0, "注册成功！");

                } else {

                    DB::rollBack();
                    $this->data = $this->makeJsCode(1, "注册失败！");

                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "注册失败！");
        }
        return response()->json($this->data);
    }
}